from django.shortcuts import render_to_response
from django.core.paginator import Paginator, InvalidPage
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.http import last_modified

from myapps.polls import models

TITLES = {'pub_date':   _('Latest Polls'),
          #the number at the end is used to indicate the position in a menu
          'votes':      _('Most Voted Polls'),
          'last_vote':  _('Recently Voted Polls'),
          'none':       _('All Polls')}


def polls_lm(request, *args, **kwargs):
    return models.Poll.last_modified()

@last_modified(polls_lm)
def index(request, limit):
    try:
        page = int(request.GET.get('p', 1))
    except ValueError:
        page = 1
        
    order_by = request.GET.get('o', 'pub_date')
    try:
        fetcher = models.Poll.fetcher(order_by, limit)
    except KeyError:
        fetcher = models.Poll.fetcher('none', limit)
      
    paginator = Paginator(fetcher, limit) #limit is also used as an argument to fetcher
    try:
        polls = paginator.page(page)
    except InvalidPage:
        polls = paginator.page(paginator.num_pages)
    
    count = models.Poll.count() 
    title = TITLES.get(order_by) or TITLES['none']
    
    return render_to_response('polls/index.html',
        {'polls': polls,
         'count': count,
         'title': title,
         'order_by': order_by})
    